<template>
  <div style="height: 100%">
    <course :dropCourse="dropCourse" :tip="'删除'" :curriculum="curriculum">
      <el-button
        style="margin-bottom: 10px"
        @click="dialogFormVisible = true"
        type="primary"
        >创建课程
      </el-button>
    </course>
    <!-- 新建课程后的对话框 -->
    <el-dialog title="新建课程" :visible.sync="dialogFormVisible">
      <!-- 表单，用于填写课程基本信息 -->
      <el-form ref="form" :model="form" label-width="100px" size="mini">
        <el-form-item label="课程名称">
          <el-input v-model="form.name"></el-input>
        </el-form-item>
        <el-form-item label="课程背景">
          <el-input type="textarea" v-model="form.background"></el-input>
        </el-form-item>
        <el-form-item label="课程概述">
          <el-input type="textarea" v-model="form.overview"></el-input>
        </el-form-item>
        <el-form-item label="授课目标">
          <el-input type="textarea" v-model="form.teaching_target"></el-input>
        </el-form-item>
        <!-- 课程的分类/tag，允许用户选择一个存在的或者创建一个不存在的，左边label右边一个带输入建议的input，下面一个tags去显示 -->
        <!-- <el-form-item label="课程类别">
          <el-autocomplete
            class="inline-input"
            v-model="form.category"
            :fetch-suggestions="querySearch"
            placeholder="请输入内容"
            @select="handleSelect"
            @keydown.enter.native="onEnter"
          ></el-autocomplete>
          选择一个tag来展示选择任务的效果
          <el-tag
            closable
            v-for="c in form.categorys"
            :key="c"
            @close="handleClose(c)"
            >{{ c }}</el-tag
          >
        </el-form-item> -->
        <el-form-item label="课程开始日期">
          <el-date-picker
            v-model="form.start_date"
            type="date"
            placeholder="选择课程开始日期"
          ></el-date-picker>
        </el-form-item>
        <el-form-item label="课程结束日期">
          <el-date-picker
            v-model="form.end_date"
            type="date"
            placeholder="选择课程结束日期"
          ></el-date-picker>
        </el-form-item>
      </el-form>

      <!-- 上传封面 -->
      <p style="text-align: left">上传课程封面</p>
      <el-upload
        class="upload-demo"
        drag
        action="#"
        :headers="headers"
        :auto-upload="false"
        :file-list="fileList"
        :on-change="handleChange"
        :limit="1"
      >
        <img v-if="imageUrl.length != 0" :src="imageUrl" class="avatar" />
        <i v-else class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip" slot="tip">
          只能上传jpg/png文件，且不超过500kb
        </div>
      </el-upload>
      <!-- 图形处理的组件 -->
      <!-- <ImgCutter rate="2:1" @cutDown="cutDown"></ImgCutter>
      <div><img :src="baseUrl" /></div> -->

      <!-- 底部操作栏 -->
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="createCourse">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import CommonForm from "@/components/CommonForm.vue";
import Course from "../Course.vue";
// import user from "@/store/user";
import ImgCutter from "vue-img-cutter";

const dayjs = require("dayjs");
export default {
  name: "TeacherCourse",
  components: { Course, CommonForm, ImgCutter },
  data() {
    return {
      role: "teacher",
      formTemplate: [
        {
          type: "input",
          label: "课程名称",
          key: "courseName",
        },
        {
          type: "date_picker",
          label: "课程截止日期",
          placeholder: "选择截止日期",
          key: "courseDeadLine",
        },
      ],
      dialogFormVisible: false,
      imageUrl: "",
      form: {},
      headers: {
        "Content-Type": "multipart/form-data",
      },
      fileList: [],
      baseUrl: "",
      curriculum: [],
      categorys: [
        "哲学",
        "经济学",
        "法学",
        "教育学",
        "文学",
        "历史学",
        "理学",
        "工学",
        "农学",
        "医学",
        "军事学",
        "管理学",
        "艺术学",
      ],
    };
  },
  methods: {
    // handleClose(tag) {
    //   // console.log('tag: ', tag);
    //   this.form.categorys = this.form.categorys.filter((c) => c != tag);
    // },
    // onEnter() {
    //   // console.log(this.form.category);
    //   this.form.categorys.push(this.form.category);
    //   this.form.category = "";
    // },
    // 将categorys转成需要的结构
    // initCategorys() {
    //   this.categorys = this.categorys.map((v) => ({ value: v }));
    // },
    // handleSelect(item) {
    //   this.form.categorys.push(item.value);
    //   this.form.category = "";
    // },
    // querySearch(queryString, cb) {
    //   var categorys = this.categorys;
    //   var results = queryString
    //     ? categorys.filter(this.createFilter(queryString))
    //     : categorys;
    //   // 调用 callback 返回建议列表的数据
    //   cb(results);
    // },
    // createFilter(queryString) {
    //   return (category) => {
    //     return category.value.indexOf(queryString) === 0;
    //   };
    // },
    handleChange(file, fileList) {
      this.fileList = fileList;
    },
    getAndSetTeachCourse(teacher_id) {
      // const {teacher_id} = this.user;
      // 请求教员
      this.axios
        .get(`${this.$reqPrefix}/getTeachCourse?teacher_id=${teacher_id}`)
        .then((res) => {
          this.curriculum = res.data.data || [];
        });
    },
    createCourse() {
      // 上传
      const { teacher_id } = this.user;
      // console.log(this.fileList);
      // 对课程里面的时间进行一个格式调整
      this.form.end_date = dayjs(this.form.end_date).format(
        "YYYY-MM-DD HH:mm:ss"
      );
      this.form.start_date = dayjs(this.form.start_date).format(
        "YYYY-MM-DD HH:mm:ss"
      );

      // 先上传封面图片
      let images = new FormData();
      this.fileList.forEach((val) => {
        images.append("file", val.raw);
      });
      this.axios
        .post(`${this.$reqPrefix}/upload`, images)
        .then((res) => res.data.data[0].url)
        .then((imgSrc) => {
          // this.imageUrl = imgSrc;
          this.form.cover = imgSrc;
          this.axios
            .post(`${this.$reqPrefix}/createCourse`, {
              teacher_id,
              course: this.form,
            })
            .then(() => {
              //更新本地数据
              // this.curriculum.push(this.form)
              this.getAndSetTeachCourse(this.user.teacher_id);
              //关闭弹窗
              this.dialogFormVisible = false;
              //清空数据
              this.form = {};
            }); //
        });
      // this.axios
      //     .post(`${this.$reqPrefix}/createCourse`, {
      //       teacher_id,
      //       course: this.form,
      //     })
      //     .then(() => {
      //       //更新本地数据
      //       // this.curriculum.push(this.form)
      //       this.getAndSetTeachCourse(this.user.teacher_id);
      //       //关闭弹窗
      //       this.dialogFormVisible = false;
      //       //清空数据
      //       this.form = {};
      //     }); //
    },
    cutDown(res) {
      // 裁剪结束后的base64编码
      console.log(res);
      this.baseUrl = res.dataURL;
    },
    //  提供给其他组件的dropCourse方法
    dropCourse(course_id) {
      this.curriculum = this.curriculum.filter(
        (course) => course.course_id !== course_id
      );
    },
  },
  mounted() {
    this.user = JSON.parse(localStorage.getItem("userInfo"));
    this.getAndSetTeachCourse(this.user.teacher_id);
    // this.initCategorys();
  },
};
</script>

<style lang='less' scoped>
.el-form {
  .el-form-item {
    display: flex;
  }
}
</style>